package com.jielin.handling.service.record.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jielin.handling.entity.record.RecordApply;
import com.jielin.handling.entity.record.RecordDetailed;
import com.jielin.handling.entity.vo.record.RecordApplyParams;
import com.jielin.handling.entity.vo.record.RecordApplyVo;
import com.jielin.handling.entity.vo.record.RecordDetailedPoliceManVo;
import com.jielin.handling.mapper.record.RecordApplyMapper;
import com.jielin.handling.mapper.record.RecordDetailedMapper;
import com.jielin.handling.page.DataGridBuilder;
import com.jielin.handling.service.record.RecordApplyService;
import com.jielin.handling.util.ConstantUtil;
import com.jielin.handling.util.DateUtil;
import com.jielin.handling.util.StringUtil;
import com.jielin.handling.util.lucene.Indexer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 笔录申请查看
 *
 * @author WR
 * @date 2020/10/13
 */
@Service
public class RecordApplyServiceImpl implements RecordApplyService {
    @Autowired
    private RecordApplyMapper recordApplyMapper;
    @Autowired
    private RecordDetailedMapper recordDetailedMapper;

    @Override
    public DataGridBuilder findRecordApply(RecordApplyParams recordApplyParams) {
        recordApplyParams.setPoliceNameOrCode(StringUtil.escapeMysqlChars(recordApplyParams.getPoliceNameOrCode()));
        Page<RecordApplyVo> startPage = PageHelper.startPage(recordApplyParams.getPageNum(), recordApplyParams.getPageSize());
        List<RecordApplyVo> result = recordApplyMapper.findRecordApply(recordApplyParams);
        // 查看类型:true=个人申请,false=他人申请
        result.forEach(item -> {
            String nin = recordApplyParams.getCatType() ? "您" : "";
            String content = nin + "申请查看" + item.getCaseName() + "案件中涉案人员" + item.getSuspectName() + "的笔录文件";
            switch (item.getIsPass()) {
                case "0": {
                    item.setContent("已拒绝" + content);
                }
                break;
                case "1": {
                    item.setContent("已同意" + content);
                    boolean isExpired = getIsExpired(item);
                    item.setIsExpired(isExpired);
                    item.setApplyDaysContent(getContentByDate(item.getApplyDays(), isExpired));
                }
                break;
                default: {
                    item.setContent(content);
                }
                break;
            }
        });
        return DataGridBuilder.builder().list(result).total(startPage.getTotal()).build();
    }

    @Override
    public int updateRecordApply(RecordApply recordApply) {
        return recordApplyMapper.update(recordApply);
    }

    @Override
    public String findPassRecord(String id, String policeId) {
        RecordApply recordApply = recordApplyMapper.findRecordApplyByPoliceId(id, policeId);
        // 没有过期
        if (!getIsExpired(RecordApplyVo.builder().applyDays(recordApply.getApplyDays()).applyPassDate(recordApply.getApplyPassDate()).build())) {
            String path = recordDetailedMapper.findPathById(recordApply.getRecordDetailedId());
            if (!StringUtil.isEmpty(path)) {
                return ConstantUtil.returnIp() + path;
            }
        }
        return null;
    }

    @Override
    public DataGridBuilder findMyRecord(RecordApplyParams recordApplyParams) {
        Page<RecordDetailedPoliceManVo> startPage = PageHelper.startPage(recordApplyParams.getPageNum(), recordApplyParams.getPageSize());
        List<RecordDetailedPoliceManVo> result = recordDetailedMapper.findDetailedByRecordPoliceId(recordApplyParams.getPoliceId(), null, null);
        result.forEach(item -> {
            item.setContent(item.getCaseName() + "案件中涉案人员" + item.getSuspectName() + "的笔录文件");
            item.setPath(ConstantUtil.returnIp() + item.getPath());
        });
        return DataGridBuilder.builder().list(result).total(startPage.getTotal()).build();
    }

    @Override
    public int addRecordApply(RecordApply recordApply) {
        recordApply.setId(StringUtil.generatorUUID());
        recordApply.setApplyDate(new Date());
        recordApply.setApplyDays(0);
        return recordApplyMapper.insert(recordApply);
    }

    @Override
    public DataGridBuilder findRecord(RecordApplyParams recordApplyParams) {
        // 1.搜索笔录内容，截取文本上下5行
        //


        return null;
    }

    @Override
    public Map findMyRecordGroupDate(RecordApplyParams recordApplyParams) {
        // 默认分页10条数据
//        recordApplyParams.setPageNum(1);
//        recordApplyParams.setPageSize(10);
        DataGridBuilder dataGrid = findMyRecord(recordApplyParams);
        List<RecordDetailedPoliceManVo> list = (List<RecordDetailedPoliceManVo>) dataGrid.getList();

        // 今天
        Date todayDate = DateUtil.getDateByBaseStr(DateUtil.getNowDate(), DateUtil.DATE_FORMAT_REDUCE);
        // 昨天
        Date yesterdayDate = DateUtil.getAgoSeveralDays(todayDate, 1);
        // 上周一
        Date lastWeekStartDate = DateUtil.getLastWeekMonday(todayDate);
        // 上周日
        Date lastWeekEndDate = DateUtil.getLastWeekSunday(todayDate);

        List<RecordDetailedPoliceManVo> todayResult = list.stream()
                .filter(item -> DateUtil.getDaySubFormatReduce(todayDate, item.getEndDate()) == 0)
                .collect(Collectors.toList());
        list.removeAll(todayResult);
        List<RecordDetailedPoliceManVo> yesterdayResult = list.stream()
                .filter(item -> DateUtil.getDaySubFormatReduce(yesterdayDate, item.getEndDate()) == 0)
                .collect(Collectors.toList());
        list.removeAll(yesterdayResult);
        List<RecordDetailedPoliceManVo> lastWeekResult = list.stream()
                .filter(item -> (DateUtil.getDaySubFormatReduce(lastWeekStartDate, item.getEndDate()) >= 0)
                        && (DateUtil.getDaySubFormatReduce(lastWeekEndDate, item.getEndDate()) <= 0))
                .collect(Collectors.toList());
        list.removeAll(lastWeekResult);
        List<RecordDetailedPoliceManVo> earlierResult = list.stream()
                .filter(item -> DateUtil.getDaySubFormatReduce(lastWeekStartDate, item.getEndDate()) < 0)
                .collect(Collectors.toList());
        // 移除完数据剩下前天与本周一的数据，这部分数据不做展示
        list.removeAll(earlierResult);

        Map<String, Object> returnResult = new HashMap<>(8);
        returnResult.put("today", todayResult);
        returnResult.put("todayNum", todayResult.size());
        returnResult.put("yesterday", yesterdayResult);
        returnResult.put("yesterdayNum", yesterdayResult.size());
        returnResult.put("lastWeek", lastWeekResult);
        returnResult.put("lastWeekNum", lastWeekResult.size());
        returnResult.put("earlier", earlierResult);
        returnResult.put("earlierNum", dataGrid.getTotal() - todayResult.size() - yesterdayResult.size() - lastWeekResult.size() - list.size());
        return returnResult;
    }

    @Override
    public void updateRecordLuceneIndex() {
        // 未建立索引的记录
        List<RecordDetailed> noIndexRecord = recordDetailedMapper.findNoIndexRecord();
        if (noIndexRecord.size() > 0) {
            List<File> files = new ArrayList<>(noIndexRecord.size());
            List<String> ids = new ArrayList<>(noIndexRecord.size());
            noIndexRecord.forEach(recordDetailed -> {
//                files.add(new File(recordDetailed.getPdfPath()));
                // win环境下测试
                files.add(new File(recordDetailed.getPdfPath()));
                ids.add(recordDetailed.getId());
            });
            try {
                // 更新索引文件
                Indexer.IndexerUpdateRecord(ConstantUtil.INDEX_DIR, files.stream().distinct().collect(Collectors.toList()));
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 更新已建立索引的记录状态
            recordDetailedMapper.updateDetailedIsIndex(ids);
        }

    }

    private static String getContentByDate(int days, boolean isExpired) {
        String content = "有效期：";
        if (isExpired) {
            content = "已过查询期限";
        } else {
            switch (days) {
                case 1:
                    content += "1天";
                    break;
                case 7:
                    content += "1周";
                    break;
                case 30:
                    content += "1个月";
                    break;
                default:
                    content = "";
                    break;
            }
        }
        return content;
    }

    private boolean getIsExpired(RecordApplyVo recordApplyVo) {
        return DateUtil.getSecondSub(new Date(), DateUtil.getAfterSeveralDays(recordApplyVo.getApplyPassDate(), recordApplyVo.getApplyDays())) <= 0;
    }


}
